<!--suppress HtmlDeprecatedAttribute -->
<script setup lang="ts">
import CustomIcon from "@/components/framework/icon";
import { hc } from "@/framework/vue/util/render";
import { CheckOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { computed, ref, shallowRef, watch } from "vue";
import { nodejsMirrorList, versionList2TreeData } from "@/pages/tools/nodejs/mirror/nodejs-mirror";
import type { DataNode } from "ant-design-vue/es/vc-tree/interface";
import { message, Modal } from "ant-design-vue";
import { noop } from "@/framework/util/warning";
import NodejsVersionItem from "@/pages/tools/nodejs/nodejs-version-item.vue";
import { useNodejsStore } from "@/pages/tools/nodejs/nodejs-store";
import { useLocalRef } from "@/framework/vue/hooks";
import type { GenericToolItemVO } from "@/pages/tools/common/vos";
import { openExternal } from "@/framework/util/shell";
import PendingButton from "@/components/framework/pending-button.vue";

const nodejsStore = useNodejsStore();
const dataSource = computed(() => nodejsStore.installedVersionList);

// 安装弹窗

const installModalOpen = ref(false);
const onlyShowLtsVersion = useLocalRef("nodejs.install.onlyShowLtsVersion", true);
const showAll = useLocalRef("nodejs.install.showAll", false);
const versionsTreeData = shallowRef<DataNode[]>([]);
const renderVersionsTreeData = computed(() => {
  let data = versionsTreeData.value;
  if (onlyShowLtsVersion.value && nodejsStore.nodeConfig.ltsVersions) {
    const ltsVersions = nodejsStore.nodeConfig.ltsVersions.split(",");
    data = data.filter(it => ltsVersions.includes(it.key as string));
  }
  if (!showAll.value) {
    for (let i = 0; i < data.length; i++) {
      const datum = data[i];
      data[i] = { ...datum, children: datum.children?.slice(0, 1) };
    }
  }
  return data;
});
const expandedKeys = ref<string[]>([]);
const versionDataLoading = ref(false);

watch(renderVersionsTreeData, list => {
  expandedKeys.value = list.length > 0 ? [list[0].key as string] : [];
});

const loadVersionsData = async () => {
  versionDataLoading.value = true;
  try {
    const versionList = await nodejsMirrorList[0].getVersionList();
    versionsTreeData.value = versionList2TreeData(versionList);
  } catch (e: any) {
    message.error(e?.message || "加载版本列表失败");
  } finally {
    versionDataLoading.value = false;
  }
};

const openInstallModal = async () => {
  installModalOpen.value = true;
  if (versionsTreeData.value.length === 0) {
    loadVersionsData().catch(noop);
  }
};

const toggleItemExpand = (key: string) => {
  if (expandedKeys.value.includes(key)) {
    expandedKeys.value.splice(expandedKeys.value.indexOf(key), 1);
  } else {
    expandedKeys.value.push(key);
  }
};

// 安装弹窗 END

const uninstall = async (record: GenericToolItemVO) => {
  Modal.confirm({
    title: "提示",
    content: "确定要卸载该版本吗？",
    centered: true,
    onOk: async () => {
      await nodejsStore.uninstallVersion(record);
      message.success("卸载成功");
    },
  });
};
const setDefault = async (record: GenericToolItemVO) => {
  await nodejsStore.setDefaultVersion(record);
  message.success("设置成功");
};
</script>

<template>
  <div class="full-view overflow-auto ph-16">
    <div class="mb-16 flex">
      <a-button type="primary" :icon="hc(PlusOutlined)" @click="openInstallModal">安装</a-button>
    </div>
    <a-table size="small" bordered :data-source="dataSource" :pagination="{ pageSize: 15, hideOnSinglePage: true, size: 'middle' }">
      <a-table-column title="版本名称" data-index="version" width="160px" align="center">
        <template v-slot="{ text }">
          <b>v{{ text }}</b>
        </template>
      </a-table-column>
      <a-table-column title="系统默认" width="100px" align="center">
        <template v-slot="{ record }">
          <CheckOutlined v-if="record.version === nodejsStore.currentVersion?.version" class="color-success" />
        </template>
      </a-table-column>
      <a-table-column title="安装路径" data-index="installPath" align="center">
        <template v-slot="{ text }">
          <a-button type="link" @click="openExternal(text)">{{ text }}</a-button>
        </template>
      </a-table-column>
      <a-table-column title="操作" width="300px">
        <template v-slot="{ record }">
          <a-space>
            <a-button type="text" size="small" danger :icon="hc(DeleteOutlined)" @click="uninstall(record)">卸载</a-button>
            <pending-button type="text" size="small" v-if="record.version !== nodejsStore.currentVersion?.version" :fn="setDefault" :fn-args="record"
              >设为默认
            </pending-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <a-modal title="安装" centered v-model:open="installModalOpen">
      <a-spin :spinning="versionDataLoading">
        <a-tree :height="500" :tree-data="renderVersionsTreeData" v-model:expanded-keys="expandedKeys" block-node default-expand-all class="mv-10">
          <template #title="{ key, title, top, lastModified }">
            <div v-if="top" class="flex-sb pr-10" @click="toggleItemExpand(key)">
              <a-space>
                <custom-icon type="icon-nodejs" class="mr-5" />
                <span style="font-size: 14px">{{ title }}</span>
              </a-space>
            </div>
            <nodejs-version-item v-else :version="title" :last-modified="lastModified" />
          </template>
        </a-tree>
      </a-spin>
      <template #footer>
        <div class="flex-sb">
          <a-space>
            <a-checkbox v-model:checked="onlyShowLtsVersion">只显示LTS版本</a-checkbox>
            <a-checkbox v-model:checked="showAll">显示全部</a-checkbox>
          </a-space>
          <a-space>
            <a-button type="default" @click="loadVersionsData">刷新</a-button>
            <a-button type="default" @click="installModalOpen = false">取消</a-button>
          </a-space>
        </div>
      </template>
    </a-modal>
  </div>
</template>
